package com.example.springmvc.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.lang.reflect.Method;

public class HandlerAdapter {

    public Object handle(HttpServletRequest request, HttpServletResponse response, HandlerMapping handlerMapping) throws Exception {
        // 获取目标方法
        Method method = handlerMapping.getMethod();
        // 获取方法参数类型
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 根据参数类型构造参数数组
        Object[] args = new Object[parameterTypes.length];

        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameterTypes[i] == HttpServletRequest.class) {
                args[i] = request;
            } else if (parameterTypes[i] == HttpServletResponse.class) {
                args[i] = response;
            } else {
                throw new IllegalArgumentException("Unsupported parameter type: " + parameterTypes[i].getName());
            }
        }
        // 调用目标方法
        return method.invoke(handlerMapping.getController(), args);
    }
}